package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.uuid.UUID;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备Service业务层处理
 * 
 * @author alexis
 * @date 2025-10-13
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient client;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询设备
     *
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id) {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备列表
     *
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return deviceMapper.insert(device);
    }

//    /**
//     * 修改设备
//     *
//     * @param device 设备
//     * @return 结果
//     */
//    @Override
//    public int updateDevice(Device device)
//    {
//        return deviceMapper.updateById(device);
//    }

    /**
     * 批量删除设备
     *
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

//    /**
//     * 删除设备信息
//     *
//     * @param id 设备主键
//     * @return 结果
//     */
//    @Override
//    public int deleteDeviceById(Long id) {
//        return deviceMapper.deleteById(id);
//    }

    @Override
    public void syncProductList() {
        //请求参数
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        //设置条数
        listProductsRequest.setLimit(50);
        //发起请求
        ListProductsResponse response = client.listProducts(listProductsRequest);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }
        //存储到redis

        redisTemplate.opsForValue().set(CacheConstants.ALL_PRODUCT_KEY, JSONUtil.toJsonStr(response.getProducts()));

    }

    /**
     * 查询所有产品
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        String jsonStr = redisTemplate.opsForValue().get(CacheConstants.ALL_PRODUCT_KEY);
        if (jsonStr == null) {
            return Collections.emptyList();
        }
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }

    /**
     * 注册设备
     *
     * @param deviceDto
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //1. 判断设备名称是否重复
        Long count = lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()).count();
        if (count > 0) {
            throw new BaseException("设备名称重复");
        }
        //2. 判断设备标识是否重复
        count = lambdaQuery().eq(Device::getNodeId, deviceDto.getNodeId()).count();
        if (count > 0) {
            throw new BaseException("设备标识重复");
        }
        //判断如果是随身设备，将物理位置设置为-1
        if (deviceDto.getLocationType() == 0) {
            deviceDto.setPhysicalLocationType(-1);
        }
        //3. 判断同一位置是否绑定了相同的产品
        count = lambdaQuery().eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .count();
        if (count > 0) {
            throw new BaseException("同一位置已绑定相同产品");
        }
        //4. 注册设备到华为iot平台
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        AddDeviceRequest addDeviceRequest = new AddDeviceRequest();
        AddDevice addDevice = new AddDevice();
        addDevice.withDeviceName(deviceDto.getDeviceName())
                .withProductId(deviceDto.getProductKey())
                .withAuthInfo(new AuthInfo().withSecret(uuid))
                .withNodeId(deviceDto.getNodeId());
        addDeviceRequest.withBody(addDevice);
        AddDeviceResponse response = null;
        try {
            response = client.addDevice(addDeviceRequest);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 注册设备失败");
        }
        //随机生成密钥
        //5.保存设备数据到数据库
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setSecret(uuid);
        device.setIotId(response.getDeviceId());
        save(device);
    }

    @Override
    public DeviceDetailVo getDeviceDetail(String iotId) {
        //查询数据库
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (device == null) {
            log.error("设备不存在");
            throw new BaseException("设备不存在");

        }
        //调用华为云物联网接口
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response;
        try {
            response = client.showDevice(request);
        } catch (Exception e) {
            log.error("物联网接口 - 获取设备详情失败");
            throw new BaseException("物联网接口 - 查询设备详情失败");
        }
        //属性拷贝
        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        deviceDetailVo.setDeviceStatus(response.getStatus());
        //日期时区转换
        String activeTimeStr = response.getActiveTime();
        if (StringUtils.isNotEmpty(activeTimeStr)) {
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            //日期时区转换
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            deviceDetailVo.setActiveTime(activeTime);
        }
        return deviceDetailVo;
    }

    /**
     * 查询设备服务属性
     *
     * @param iotId
     * @return
     */
    @Override
    public AjaxResult queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 查询设备上报数据，调用失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        if (CollUtil.isEmpty(shadow)) {
            List<Object> emptyList = Collections.emptyList();
            return AjaxResult.success(emptyList);
        }
        //返回数据
        JSONObject jsonObject = JSONUtil.parseObj(shadow.get(0).getReported().getProperties());

        List<Map<String, Object>> list = new ArrayList<>();

        //处理上报时间日期
        LocalDateTime activeTime = LocalDateTimeUtil.parse(shadow.get(0).getReported().getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
        //日期时区转换
        LocalDateTime eventTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        jsonObject.forEach((k, v) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("functionId", k);
            map.put("value", v);
            map.put("eventTime", eventTime);
            list.add(map);
        });

        return AjaxResult.success(list);

    }

    /**
     * 修改设备
     *
     * @param deviceDto 设备
     */
    @Override
    public void updateDevice(DeviceDto deviceDto) {
//        //修改数据库
//        Device device = BeanUtil.toBean(deviceDto, Device.class);
//        updateById(device);
//        //从华为物联网平台修改设备
//        UpdateDeviceRequest request = new UpdateDeviceRequest();
//        request.setDeviceId(device.getIotId());
//        UpdateDevice updateDevice = new UpdateDevice();
//        updateDevice.withDeviceName(device.getDeviceName())
//                .withDescription(device.getProductKey())
//                .withDescription(device.getNodeId());
//        request.withBody(updateDevice);
//        UpdateDeviceResponse response = client.updateDevice(request);
//        if (response.getHttpStatusCode() != 200) {
//            throw new BaseException("物联网接口 - 修改设备失败");
//        }

        Device device=getById(deviceDto.getId());
        if (device==null){
            throw new BaseException("设备不存在");
        }
        //判断设备名称是否重复
        Long count = lambdaQuery()
                .eq(Device::getDeviceName,deviceDto.getDeviceName())
                .ne(Device::getId,deviceDto.getId()).count();
        if (count>0){
            throw new BaseException("设备名称已存在");
        }
        //判断接入位置是否重复
        count = lambdaQuery()
                .eq(Device::getBindingLocation,deviceDto.getBindingLocation())
                .eq(Device::getLocationType,deviceDto.getLocationType())
                .eq(Device::getProductKey,device.getProductKey())
                .eq(Device::getPhysicalLocationType,deviceDto.getPhysicalLocationType())
                .ne(Device::getId,deviceDto.getId()).count();
        if (count>0){
            throw new BaseException("设备接入位置已存在");
        }
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.withDeviceId(device.getIotId());
        UpdateDevice updateDevice = new UpdateDevice();
        updateDevice.withDeviceName(deviceDto.getDeviceName());
        request.withBody(updateDevice);
        try{
            client.updateDevice(request);
        }catch (Exception e){
            log.error("物联网接口 - 修改设备失败");
            throw new BaseException("物联网接口 - 修改设备失败");
        }
        //修改数据库
        BeanUtil.copyProperties(deviceDto,device);
        updateById(device);





    }


    /**
     * 删除设备
     *
     * @param iotId
     */
    @Override
    public boolean deleteDeviceByiotId(String iotId) {
//        DeleteDeviceRequest request = new DeleteDeviceRequest();
//        request.withDeviceId(iotId);
//        DeleteDeviceResponse response = client.deleteDevice(request);
//        if (response.getHttpStatusCode() != 200) {
//            throw new BaseException("物联网接口 - 删除设备失败");
//        }
//        return remove(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));

        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        try {
            client.deleteDevice(request);
        }catch (Exception e){
            log.error("物联网接口 - 删除设备失败");
            throw new BaseException("物联网接口 - 删除设备失败");
        }
        //从数据库中删除设备
        return remove(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));

    }

    /**
     * 查询产品详情
     * @param productKey
     * @return
     */
    @Override
    public AjaxResult queryProduct(String productKey) {
        if (productKey==null){
            throw new BaseException("产品Key不能为空");
        }
        //调用华为云端口获取产品详情
        ShowProductRequest showProductRequest = new ShowProductRequest();
        showProductRequest.setProductId(productKey);
        ShowProductResponse response ;
        try {
            response = client.showProduct(showProductRequest);
        }catch (Exception e){
            log.error("物联网接口 - 查询产品详情失败");
           throw new BaseException("物联网接口 - 查询产品详情失败");
        }
        //判断是否纯在服务数据
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if (CollectionUtils.isEmpty(serviceCapabilities)){
            return AjaxResult.success(Collections.emptyList());
        }
        return AjaxResult.success(serviceCapabilities);
    }
}

